<template>
  <div class="show-all" style="width: 1500px">
    <el-card>
      <div class="header">
        <span>{{ route.query.mode === 'edit' ? '编辑采购单' : '新增采购单' }}</span>
        <span class="required-tip">* 为必填项</span>
      </div>
        <el-form
        ref="ruleFormRef"
        style="max-width: 1500px"
        :model="ruleForm"
        :rules="rules"
        label-width="auto"
        >
        <el-row :gutter="20">
          <el-col :span="8">
<el-form-item label="采购单号" prop="purchase_Number">
<el-input v-model="ruleForm.purchase_Number" />
</el-form-item>
          </el-col>
          <el-col :span="8">
<el-form-item label="单据类型" prop="purchase__Types">
<el-select v-model="ruleForm.purchase__Types" placeholder="请选择入库类别">
<el-option label="采购中" value="采购中" />
<el-option label="全部入库" value="全部入库" />
<el-option label="部分入库" value="部分入库" />
</el-select>
</el-form-item>
          </el-col>
          <el-col :span="8">
<el-form-item label="关联订单号" prop="order_Number">
<el-input v-model="ruleForm.order_Number" />
</el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="8">
<el-form-item label="供应商名" prop="purchase__Supplier">
<el-input v-model="ruleForm.purchase__Supplier" />
</el-form-item>
          </el-col>
          <el-col :span="8">
<el-form-item label="客户名称" prop="purchase__Name">
<el-input v-model="ruleForm.purchase__Name" />
</el-form-item>
          </el-col>
          <el-col :span="8">
<el-form-item label="联系人" prop="contact_Name">
<el-input v-model="ruleForm.contact_Name" />
</el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="8">
<el-form-item label="电话" prop="purchase__Phone">
<el-input v-model="ruleForm.purchase__Phone" />
</el-form-item>
          </el-col>
          <el-col :span="8">
<el-form-item label="收货日" required>
<el-col :span="11">
<el-form-item prop="date1">
<el-date-picker
v-model="ruleForm.purchase__Day"
type="date"
aria-label=""
placeholder=""
style="width: 100%"
/>
</el-form-item>
</el-col>
</el-form-item>
          </el-col>
          <el-col :span="8">
<el-form-item label="备注" prop="purchase__Desc">
<el-input v-model="ruleForm.purchase__Desc" type="textarea" />
</el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="8">
<el-form-item label="制单人" prop="purchase__Preparer">
<el-input v-model="ruleForm.purchase__Preparer" />
</el-form-item>
          </el-col>
          <el-col :span="8">
<el-form-item label="制单时间" prop="purchase__Time">
<el-input v-model="ruleForm.purchase__Time" />
</el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>
  </div>

<div class="flex flex-wrap gap-4">
    <h2>产品信息</h2>
    <el-button type="success" plain @click="dialogTableVisible = true">+新增产品</el-button>
    
    <!-- 显示选中的产品信息 -->
    <div v-if="selectedProducts.length > 0" style="margin: 10px 0; padding: 10px; background-color: #f0f9ff; border-radius: 4px; border: 1px solid #b3d8ff;">
      <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 10px;">
        <h4 style="margin: 0; color: #409eff;">已选中的产品 ({{ selectedProducts.length }}个):</h4>
        <div style="display: flex; align-items: center; gap: 10px;">
          <span style="color: #67c23a; font-weight: bold;">选中产品总价: ¥{{ calculateSelectedTotal() }}</span>
          <el-button type="danger" size="small" @click="batchDeleteSelected">批量删除</el-button>
        </div>
      </div>
      <div style="display: flex; flex-wrap: wrap; gap: 10px;">
        <el-tag 
          v-for="product in selectedProducts" 
          :key="product.product_ID"
          type="info"
          closable
          @close="removeSelectedProduct(product.product_ID)"
        >
          {{ product.product_Name }} (ID: {{ product.product_ID }})
        </el-tag>
      </div>
    </div>
    
    <el-card style="width: 1500px" shadow="always">
      <el-table 
        ref="mainTableRef"
        :data="tableData" 
        :model="ruleForm" 
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
      <el-table-column prop="product_Name" label="产品名称" width="180" />
      <el-table-column prop="product_Number" label="产品编码" width="180" />
      <el-table-column prop="specifications" label="规格" width="180" />
      <el-table-column prop="unit_Name" label="单位" width="180" />
      <el-table-column prop="price" label="单价" width="180" />
      <el-table-column prop="product_Num" label="数量" width="180" >
        <template v-slot="scoped">
          <el-input  
            v-model="scoped.row.product_Num" 
            style="width: 120px;" 
            @input="calculateTotalPrice(scoped.row)"
            type="number"
            min="0"
          />
        </template>
      </el-table-column>
      <el-table-column label="总价" width="180" >
        <template v-slot="scoped">
          <span>{{ calculateRowTotal(scoped.row) }}</span>
        </template>
      </el-table-column>
             <el-table-column  label="操作" >
         <template v-slot="scoped">
             <el-button type="danger" @click="deleteRow(scoped.$index)">删除</el-button>
         </template>
       </el-table-column>
      </el-table>
    </el-card>
    
    <!-- 总计显示 -->
    <!-- <div style="margin-top: 20px; text-align: right; padding: 10px; background-color: #f5f7fa; border-radius: 4px;">
      <span style="font-size: 16px; font-weight: bold; color: #409eff;">
        总计: ¥{{ calculateGrandTotal() }}
      </span>
    </div> -->
</div>

<!-- 采购新增信息弹出框 -->
 <el-dialog v-model="dialogTableVisible" title="选择产品" width="1000" draggable>
    <el-form :inline="true" :model="formInline" class="demo-form-inline">
    <el-form-item label="产品编号">
      <el-input v-model="data1.Product_Number" placeholder="请输入编码" clearable />
    </el-form-item>

    <el-form-item label="产品名称">
      <el-input v-model="data1.Product_Name" placeholder="请输入名称" clearable />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="Productshow1()">搜索</el-button>
    </el-form-item>
    </el-form>

    <!-- 弹出框新增产品信息的显示 -->
    <el-table 
      ref="dialogTableRef"
      :data="gridData" 
      style="width: 1200;"
      @selection-change="handleDialogSelectionChange"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column property="product_Number" label="产品编码" width="100" />
      <el-table-column property="product_Name" label="产品名称" width="100" />
      <el-table-column property="specifications" label="规格" width="100" />
      <el-table-column property="category_Name" label="类别" width="100" />
      <el-table-column property="unit_Name" label="存储单位" width="100" />
      <el-table-column property="packaging_Type" label="包装类型" width="100" />
      <el-table-column property="price" label="单价" width="100" />
      <el-table-column property="weight" label="重量" width="100" />
    </el-table>
     <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogTableVisible = false">关闭</el-button>
        <el-button type="primary" @click="addSelectedProducts">选择</el-button>
      </div>
    </template>

  </el-dialog>


  <!-- 采购信息的点击/取消按钮 -->
<el-form-item style="margin-left: 600px;margin-top: 20px;width: 200px;">
<el-button type="primary" @click="submitForm(ruleFormRef)">{{ route.query.mode === 'edit' ? '保存修改' : '提交' }}</el-button>
<el-button @click="handleCancel">取消</el-button>
</el-form-item>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { BusinessRed } from '@/http/axiosHelper'
import { BasicsRed } from '@/http/axiosHelper'  //段
import { statementRed } from '@/http/axiosHelper'
import { BasicsWrite } from '@/http/axiosHelper'  //段
import type { FormInstance, FormRules } from 'element-plus'
interface RuleForm {
  name: string
  region: string
  count: string
  date1: string
  date2: string
  delivery: boolean
  location: string
  type: string[]
  resource: string
  desc: string
}

//单号的唯一
// 改进版 - 添加持久化支持
const generateDateBasedNumber = (incrementLength: number = 4) => {
  const now = new Date();
  const datePart = `${now.getFullYear()}${String(now.getMonth() + 1).padStart(2, '0')}${String(now.getDate()).padStart(2, '0')}`;
  
  // 从localStorage读取或初始化计数器
  const storageKey = `dateNumCounter_${datePart}`;
  let currentCount = localStorage.getItem(storageKey);
  
  // 如果localStorage中没有值，则初始化为0
  if (currentCount === null) {
    currentCount = '0';
  }
  
  // 转换为数字，递增，然后转回字符串
  const numericCount = parseInt(currentCount, 10) + 1;
  currentCount = numericCount.toString();
  
  // 保存新的计数器值
  localStorage.setItem(storageKey, currentCount);

  // 确保incrementLength是数字，然后生成递增部分
  const incrementPart = currentCount.padStart(incrementLength, '0');
  
  return datePart + incrementPart;
};

const route = useRoute()
const router = useRouter()
const ruleFormRef = ref<FormInstance>()
// 添加表格引用
const mainTableRef = ref<any>()
const dialogTableRef = ref<any>()

// 存储选中的数据
const selectedProducts = ref<any[]>([])
const dialogSelectedProducts = ref<any[]>([])

const ruleForm = reactive<{
  purchase_Number: string
  purchase__Types: string
  order_Number: string
  purchase__Supplier: string
  purchase__Name: string
  contact_Name: string
  purchase__Phone: string
  purchase__Day: string
  purchase__Desc: string
  purchase__Preparer: string
  purchase__Time: string
  product_Num: number
  product_ID: number
  refund_Num: string
  state: number
  receivable_Id: number
  warehouse_Id: number
  createUse: string
  upDateUse: string
  createTime: string
  upDataTime: string
  isDeleted: boolean
  purchase_State: number
  be_Credited: boolean
  purchase_Return: boolean
  return_Number: string
}>({
  "purchase_Number": generateDateBasedNumber(),
  "purchase__Types": "",
  "order_Number": "",
  "purchase__Supplier": "",
  "purchase__Name": "",
  "contact_Name": "",
  "purchase__Phone": "",
  "purchase__Day": "",
  "purchase__Desc": "",
  "purchase__Preparer": "",
  "purchase__Time": "",
  "product_Num": 0,
  "product_ID": 0,
  "refund_Num": "string",
  "state": 0,
  "receivable_Id": 0,
  "warehouse_Id": 0,
  "createUse": "string",
  "upDateUse": "string",
  "createTime": "2025-07-25T05:38:00.253Z",
  "upDataTime": "2025-07-25T05:38:00.253Z",
  "isDeleted": true,
  "purchase_State": 0,
  "be_Credited": true,
  "purchase_Return": true,
  "return_Number": "string"
})

//表单验证
const rules = reactive<FormRules>({
  purchase__Types: [
    { required: true, message: '请选择单据类型', trigger: 'blur' },
  ],
})

//单击保存事件 - 已合并到下面的增强版本中

//信息的重置
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}





//生命周期钩子函数
onMounted(()=>{
  // 检查是否为编辑模式
  const isEditMode = route.query.mode === 'edit'
  const editId = route.query.id
  
  if (isEditMode && editId) {
    // 编辑模式：从localStorage加载数据
    loadEditData()
  } else {
    // 新增模式：生成新的单号
    ruleForm.purchase_Number = generateDateBasedNumber()
  }
  
  Productshow()
  Productshow1()
})

// 加载编辑数据
const loadEditData = () => {
  try {
    const editData = localStorage.getItem('editPurchaseData')
    if (editData) {
      const parsedData = JSON.parse(editData)
      // 将编辑数据填充到表单
      Object.keys(parsedData).forEach(key => {
        if (key in ruleForm) {
          (ruleForm as any)[key] = parsedData[key]
        }
      })
      
      // 清空localStorage中的数据
      localStorage.removeItem('editPurchaseData')
      
      ElMessage.success('已加载编辑数据')
    }
  } catch (error: any) {
    console.error('加载编辑数据失败:', error)
    ElMessage.error('加载编辑数据失败')
  }
}



//数据信息的显示
const data = ref<{
    PageIndex: number
    PageSize: number
    totaCount: number
    Purchase_Number: string
    Product_Number: string
    Product_Name: string
    Category_ID: string
}>({
    PageIndex : 1,
    PageSize : 15,
    totaCount:0,
    Purchase_Number:'',
    Product_Number:'',
    Product_Name:'',
    Category_ID:''
})
const tableData = ref<any[]>([])
const Productshow = () =>{
  BasicsRed.get('api/Product/GetProductHandle',{
    params:{
      PageIndex:data.value.PageIndex,
      PageSize:data.value.PageSize
    }
  })
  .then((res: any) => {
  tableData.value = res.data.data;
  data.value.totaCount = res.data.totalCount
  })
  .catch((err: any) => {
    console.error('获取产品信息失败:', err)
  })
}


//新增弹出框
const dialogTableVisible = ref(false)
const dialogFormVisible = ref(false)
const formLabelWidth = '140px'

//新增弹出框产品信息显示
const gridData = ref<any[]>([])
const data1 = ref<{
    PageIndex: number
    PageSize: number
    totaCount: number
    Purchase_Number: string
    Product_Number: string
    Product_Name: string
    Category_ID: string
}>({
    PageIndex : 1,
    PageSize : 15,
    totaCount:0,
    Purchase_Number:'',
    Product_Number:'',
    Product_Name:'',
    Category_ID:''
})
const Productshow1 = () =>{
  BasicsRed.get('/api/Product/GetProductHandle',{
    params:{
      PageIndex:data1.value.PageIndex,
      PageSize:data1.value.PageSize,
      Product_Number: data1.value.Product_Number,
      Product_Name: data1.value.Product_Name,
    }
  })
  .then((res: any) => {
  gridData.value = res.data.data;
  data1.value.totaCount = res.data.totalCount
  })
  .catch((err: any) => {
    console.error('获取产品信息失败:', err)
  })
}




//新增信息搜索
const formInline = reactive<{
  product_Number: string
  product_Name: string
}>({
  product_Number: '',
  product_Name: '',
})

const onSubmit = () => {
  console.log('submit!')
}




//计算单行总价
const calculateRowTotal = (row: any) => {
  const price = parseFloat(row.price?.toString() || '0') || 0;
  const quantity = parseFloat(row.product_Num?.toString() || '0') || 0;
  const total = price * quantity;
  return total.toFixed(2);
}

//计算总价的方法
const calculateTotalPrice = (row: any) => {
  // 确保数量是数字类型
  if (row.product_Num) {
    row.product_Num = parseFloat(row.product_Num.toString());
  }
  // 触发响应式更新
  tableData.value = [...tableData.value];
}

//计算所有产品的总价
const calculateGrandTotal = () => {
  let grandTotal = 0;
  tableData.value.forEach((row: any) => {
    const price = parseFloat(row.price?.toString() || '0') || 0;
    const quantity = parseFloat(row.product_Num?.toString() || '0') || 0;
    grandTotal += price * quantity;
  });
  return grandTotal.toFixed(2);
}

//产品删除表格行
const deleteRow = (index: number) => {
  ElMessageBox.confirm(
    '确定要删除这条产品信息吗？',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
      // 从数组中移除指定索引的行
      tableData.value.splice(index, 1);
      ElMessage.success('删除成功')
    })
    .catch(() => {
      ElMessage.info('已取消删除')
    })
}

// 处理主表格选择变化
const handleSelectionChange = (selection: any[]) => {
  selectedProducts.value = selection;
  console.log('主表格选中的产品:', selectedProducts.value);
}

// 处理弹出框表格选择变化
const handleDialogSelectionChange = (selection: any[]) => {
  dialogSelectedProducts.value = selection;
  console.log('弹出框选中的产品:', dialogSelectedProducts.value);
}

// 添加选中的产品到主表格
const addSelectedProducts = () => {
  if (dialogSelectedProducts.value.length === 0) {
    ElMessage({
      type: 'warning',
      message: '请先选择产品',
    });
    return;
  }

  // 将选中的产品添加到主表格
  dialogSelectedProducts.value.forEach((product: any) => {
    // 检查产品是否已经存在
    const existingProduct = tableData.value.find((item: any) => item.product_ID === product.product_ID);
    if (!existingProduct) {
      // 添加产品到表格，设置默认数量为1
      const newProduct = {
        ...product,
        product_Num: 1
      };
      tableData.value.push(newProduct);
    } else {
      ElMessage({
        type: 'warning',
        message: `产品 ${product.product_Name} 已存在`,
      });
    }
  });

  // 清空弹出框选择
  (dialogTableRef.value as any)?.clearSelection();
  dialogSelectedProducts.value = [];
  
  // 关闭弹出框
  dialogTableVisible.value = false;
  
  ElMessage({
    type: 'success',
    message: '产品添加成功',
  });
}

// 获取选中的产品ID列表
const getSelectedProductIds = () => {
  return selectedProducts.value.map((product: any) => product.product_ID);
}

// 修改提交表单函数，包含选中的产品ID
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      // 获取选中的产品ID
      const selectedIds = getSelectedProductIds();
      console.log('提交的表单数据:', ruleForm);
      console.log('选中的产品ID:', selectedIds);
      console.log('表格中的所有产品:', tableData.value);
      
      // 检查是否为编辑模式
      const isEditMode = route.query.mode === 'edit'
      const editId = route.query.id
      
      if (isEditMode && editId) {
        // 编辑模式：调用更新API
        updatePurchaseData(editId)
      } else {
        // 新增模式：调用创建API
        createPurchaseData()
      }
    } else {
      console.log('error submit!', fields)
    }
  })
}

// 创建采购数据
const createPurchaseData = () => {
  // 这里实现创建采购单的逻辑
  ElMessage.success('采购单创建成功')
  // 可以跳转回列表页面
  router.push({ name: 'PurchShow' })
}

// 更新采购数据
const updatePurchaseData = (id: string) => {
  // 这里实现更新采购单的逻辑
  ElMessage.success('采购单更新成功')
  // 可以跳转回列表页面
  router.push({ name: 'PurchShow' })
}

// 处理取消按钮
const handleCancel = () => {
  // 返回列表页面
  router.push({ name: 'PurchShow' })
}

// 移除选中的产品
const removeSelectedProduct = (productId: number) => {
  const index = selectedProducts.value.findIndex((product: any) => product.product_ID === productId);
  if (index !== -1) {
    selectedProducts.value.splice(index, 1);
    ElMessage({
      type: 'success',
      message: `产品已移除`,
    });
  }
};

// 批量删除选中的产品
const batchDeleteSelected = () => {
  if (selectedProducts.value.length === 0) {
    ElMessage({
      type: 'warning',
      message: '请先选择要删除的产品',
    });
    return;
  }

  ElMessageBox.confirm(
    `确定要批量删除选中的 ${selectedProducts.value.length} 个产品吗？`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
      // 获取选中产品的ID列表
      const selectedIds = selectedProducts.value.map((product: any) => product.product_ID);
      
      // 从主表格中删除选中的产品
      tableData.value = tableData.value.filter((item: any) => !selectedIds.includes(item.product_ID));
      
      // 清空选中状态
      selectedProducts.value = [];
      (mainTableRef.value as any)?.clearSelection();
      
      ElMessage({
        type: 'success',
        message: '批量删除成功',
      });
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '已取消批量删除',
      });
    });
};

// 计算选中产品的总价
const calculateSelectedTotal = () => {
  let total = 0;
  selectedProducts.value.forEach((product: any) => {
    const price = parseFloat(product.price?.toString() || '0') || 0;
    const quantity = parseFloat(product.product_Num?.toString() || '0') || 0;
    total += price * quantity;
  });
  return total.toFixed(2);
};

</script>

<style scoped>
.show-all {
  padding: 24px;
}
.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}
.required-tip {
  color: #f56c6c;
  font-size: 14px;
}
.purchase-form {
  max-width: 1200px;
}
</style>
